

var NZselector = Class.create({	
	/*
	 * 
	 */
	init: function(id, opts){
		
		this.item = $('#'+id);
		this.nzitem = '#'+id+'_nzselector';
		this.id = id;
		this.msgdefault = "";
		this.multiselect = this.item.attr('multiple');
		this.items_options = [];	
		this.items_binds = [];				
		
		this.options = new Object({
			default_theme: true,
			whereToPlace: '',
			onOptionSelect:function(){}
		});		
		
		$.extend(true, this.options, opts);
		
		if(!$(this.nzitem).length){
			this.getOptions();
			this.setInterface();
		}
			
	},
	
	
	/*
	 * Este metodo añade las css necesarias del selector, busca en donde se va crear el nuevo selector
	 */
	setInterface: function(){	
		var that = this;
		
		$(this.item).hide();
		
		if(this.multiselect)
			var nzHtml = this.getMultipleInterface();
		else
			var nzHtml = this.getSimpleInterface();
		
		var ready = false;		
		if(this.options.whereToPlace != ''){
			if($('#'+this.options.whereToPlace).length !=0){				
				$('#'+this.options.whereToPlace).append(nzHtml);
				ready = true;
			}else{
				alert('Error Container no encontrado.');
			}			
		}else{
			$(this.item).parent().append(nzHtml);
			ready = true;
		}
		
		if(ready)
			this.openSelector();
			
	},
	/*
	 *	Construye el contenido HTML del NZselector. 
	 *nzHtml += '<div class="nzselector_selected">'+that.msgdefault+'</div></div>';
	 */
	getSimpleInterface: function(){
		var that = this;
		
		var nzHtml = '<div id="'+this.id+'_nzselector" class="nzselector';
		if(this.options.default_theme)
			nzHtml += ' default_theme';
		nzHtml += '">';
			nzHtml += '<div class="nzselectorheader">'+that.msgdefault+'</div>';
			nzHtml += '<div class="nzselectoroptions" style="display:none;">';
			$.each(that.items_options , function(i ,e){
				
				if(e.group_cabecera){
					if(!e.default_optgroup){
						nzHtml += '<div class="nzlabel">'+e.group_label+'</div>';
					}else{
						nzHtml += '<div nz_option_id="'+e.value+'" class="nzlabel nzoptgroup nz_optgroup_id_'+e.value+' ';
							if(e.selected == true)	
								nzHtml += 'selected ';
						nzHtml += '">'+e.group_label+'</div>';
					}		
				}
				
				if(!e.default_optgroup) {
					nzHtml += '<div nz_option_id="'+e.value+'" class="nzoption nz_option_id_'+e.value+' ';
					if(e.selected == true)	
						nzHtml += 'selected ';
					nzHtml += '">'+e.text_value+'</div>';
				}
										
			});	
			nzHtml += '</div>';
		nzHtml += '</div>';
		
		return nzHtml;
		
	},
	/*
	 * 
	 */
	getMultipleInterface: function(){
		
		return false;
		
	},
	/*
	 *  Recorre los options del select original y crea una array de cada opcion con los atributos necesarios 
	 */
	getOptions: function(){
		var that = this;

		var arrayGrupo = new Array();
		
		$(this.item).find('option').each(function(i,e){
			var arrayItem = new Array();
				arrayItem['value'] = e.value; 									// Valor del option
				arrayItem['text_value'] = $(e).html(); 							// Texto que se muestra
				
			var grupo = $(e).parents('optgroup');	
				if(grupo.length > 0){

					arrayItem['group_label'] = grupo.attr('label'); // Grupo no que esta
					
					if( typeof(arrayGrupo[grupo.attr('label')]) == "undefined" ){
						
						// primer option de grupo
						if($(e).attr('default_optgroup')) {
							arrayGrupo[grupo.attr('label')] = $(e).val();
							arrayItem['group_cabecera'] = grupo.attr('label');
							arrayItem['default_optgroup'] = 1;
														
						}
						else {
							arrayGrupo[grupo.attr('label')] = null;
							arrayItem['group_cabecera'] = grupo.attr('label');
						}

					}

				}

				if(!that.multiselect && $(e).attr('selected')){  				//Comprueba si el selector no es multiselect y si la opcion esta seleccionada ... si se cumple la condicion coloca el texto en la cabecera y la marca como seleccionada 
					that.msgdefault =  '<div nz_option_id="'+e.value+'" class="nzoption nz_option_id_'+e.value+' selected">'+$(e).html()+'</div>';
					arrayItem['selected'] = true;
				}else{
					arrayItem['selected'] = false;
				}

			var length = that.items_options.length;	
			that.items_options[length] = arrayItem;				
		});


	},
	/*
	 * 
	 */
	openSelector: function(){
		var that = this;
		$(this.nzitem).find('.nzselectorheader').click(function(){	
			$(that.nzitem).find('.nzselectoroptions').show();			
			that.asignBinds();
		});
	},
	/*
	 * 
	 */
	asignBinds: function(){
		var that = this;		
		
		if(this.items_binds.length == 0){
			
			
			this.items_binds[this.items_binds.length] = $('body').click(function(e){	
				if($(e.target).parents(that.nzitem).length == 0)
						that.hideOptions();		
			});		
			
			this.items_binds[this.items_binds.length] = $(this.nzitem).find('.nzoption').click(function(e){
				
				$(that.item).val($(e.target).attr('nz_option_id'));														
				that.hideOptions();					
				
				var nz_element = $(e.currentTarget).clone();
				$(that.nzitem).find('.nzselectorheader').html(nz_element);		
				
				$(that.nzitem).find('.selected').removeClass('selected');	
				$(e.target).addClass('selected');
				
				that.item.trigger("change");
				that.options.onOptionSelect();														
			});
			
			this.items_binds[this.items_binds.length] = $(this.nzitem).find('.nzoptgroup').click(function(e){
				
				$(that.item).val($(e.target).attr('nz_option_id'));														
				that.hideOptions();					
				
				var nz_element = $(e.currentTarget).clone();
				$(that.nzitem).find('.nzselectorheader').html(nz_element);		
				
				$(that.nzitem).find('.selected').removeClass('selected');	
				$(e.target).addClass('selected');
				
				that.item.trigger("change");
				that.options.onOptionSelect();														
			});
		
		}
	},
	/*
	 * 
	 */
	destroyBinds: function(){
		$.each( this.items_binds, function(index, elem){
			$(elem).unbind();
		});	
		this.items_binds = [];
	},
	/*
	 * 
	 */
	hideOptions: function(){
			$(this.nzitem).find('.nzselectoroptions').hide();
			this.destroyBinds();
	}
});
